package com.iss.card.view.mycard;

import java.util.ArrayList;
import java.util.List;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.iss.card.CardController;
import com.iss.card.CardController.EventType;
import com.iss.card.R;
import com.iss.card.cache.BitmapConfig;
import com.iss.card.cache.ImageDataManager;
import com.iss.card.common.ApplicationManager;
import com.iss.card.common.CardTypeUtil;
import com.iss.card.common.CommonValue;
import com.iss.card.common.FunctionUtil;
import com.iss.card.common.IBackKeyListener;
import com.iss.card.common.Tools;
import com.iss.card.model.UserInfo;
import com.iss.card.view.model.ResponseBean;
import com.iss.card.view.overrideview.PullListView;
import com.iss.card.view.overrideview.PullListView.OnRefreshListener;
import com.iss.card.webservice.BaseModel;
import com.iss.card.webservice.WebServiceAsyncService;
import com.iss.card.webservice.WebServiceAsyncServiceHelper;
import com.iss.card.webservice.WebServiceAsyncService.Operation;
import com.iss.card.webservice.WebServiceAsyncService.PostExecute;
import com.iss.card.webservice.WebServiceManager.WebServiceRegistrationParameter;
import com.iss.card.webservice.WebServiceManager.WebServiceUrlPortManager;
import com.iss.card.webservice.WebServiceUtils;

public class MyCardView implements OnClickListener, IBackKeyListener,
		OnRefreshListener {
	private final static String TAG = MyCardView.class.getSimpleName();
	private FragmentActivity mContext;
	private TextView nameVal,titleTv;
	private ImageView mPendingOrder, usrHeadIcon;
	private UserInfo usrInfo;
	private PullListView scrollViewRefresh;
	private Button searchButton;
	private ImageButton searchBoxToggleButton;
	private EditText searchBox;
	private ArrayList<CardBagModel> cardBagInfos;
	private String[] cardIssuersListStrings;
	private boolean isSearchButtonShow = true;
	private RelativeLayout searchBar;

	CardItemAdapter adapter;

	public void initView() {
		final int headIconWidth = (int) mContext.getResources().getDimension(
				R.dimen.DIM_ACCOUNT_HEAD_ICON_WIDTH);
		final int headIconHeight = (int) mContext.getResources().getDimension(
				R.dimen.DIM_ACCOUNT_HEAD_ICON_HEIGHT);
		usrInfo = FunctionUtil.getCurrentLogInUser();
		nameVal.setText(usrInfo.getUsrMobile());
		String iconPath = usrInfo.getUsrHeadIconUrl();

		if (CommonValue.STR_EMPTY.equals(iconPath)) {
			usrHeadIcon.setImageBitmap(null);
		} else {
			// ImageDataManager.instance().setLoadingImage(null);
			ImageDataManager.instance().loadBitmap(iconPath, usrHeadIcon,
					new BitmapConfig(headIconWidth, headIconHeight));
		}

		if (ApplicationManager.IS_CARD_LIST_BY_STORE_ID) {
			isSearchButtonShow = false;
			
		}
		setSearchButton();
	}

	public MyCardView(FragmentActivity context, View view) {
		this.mContext = context;

		cardBagInfos = new ArrayList<CardBagModel>();
		isSearchButtonShow = true;
		titleTv = ((TextView)view.findViewById(R.id.job_name_val));
		if(!ApplicationManager.IS_CARD_LIST_BY_STORE_ID){
			titleTv.setText(R.string.tab_menu_card_bag);
		}else {
			titleTv.setText("搜索结果");
		}
		nameVal = (TextView) view.findViewById(R.id.tv_card_user_name);
		mPendingOrder = (ImageView) view
				.findViewById(R.id.iv_card_pending_order);
		usrHeadIcon = (ImageView) view
				.findViewById(R.id.iv_card_user_head_icon);

		searchBoxToggleButton = (ImageButton) view
				.findViewById(R.id.job_button);
		searchBox = (EditText) view
				.findViewById(R.id.my_card_view_search_input);
		searchButton = (Button) view.findViewById(R.id.btn_do_search);
		searchBar = (RelativeLayout) view
				.findViewById(R.id.my_card_view_search_bar);

		searchBoxToggleButton.setVisibility(View.VISIBLE);
		searchBar.setVisibility(View.GONE);
		searchBar.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				return true;
			}
		});

		searchBox.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				// TODO Auto-generated method stub
				if (actionId == EditorInfo.IME_ACTION_DONE) {
					InputMethodManager imm = (InputMethodManager) v
							.getContext().getSystemService(
									Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

					searchBar.setVisibility(View.GONE);
					ArrayList<CardBagModel> destinyArray = doSearch(
							cardIssuersListStrings, cardBagInfos, searchBox
									.getText().toString());
					adapter.setList(destinyArray);
					isSearchButtonShow = false;
					setSearchButton();

					return true;
				}
				return false;
			}
		});

		searchBoxToggleButton.setOnClickListener(this);
		searchButton.setOnClickListener(this);
		mPendingOrder.setOnClickListener(this);
		scrollViewRefresh = (PullListView) view
				.findViewById(R.id.cardlist_scrollview);
		scrollViewRefresh.setonRefreshListener(this);
		initView();
		doAsyncService();
	}

	public void doAsyncService(){
		if(ApplicationManager.IS_CARD_LIST_BY_STORE_ID){
			getCardListByStoreId();
		}else {
			getCardList();
		}
	}
	public void getCardListByStoreId(){
		String obj[] = {FunctionUtil.getCurrentLoginUserMobile(), ApplicationManager.STORE_ID_FOR_CARD_LIST};
		Log.d("kitexy debug", "STORE_ID_FOR_CARD_LIST ===> " + ApplicationManager.STORE_ID_FOR_CARD_LIST);
		WebServiceAsyncService webService = new WebServiceAsyncService();
		webService.setParameterToAsyncService(mContext,
				webService.getNextToken(), 
				Operation.OP_SERVICE_ARG_GET_CARD_LIST_BY_STORE_ID,
				WebServiceRegistrationParameter.PARAMETERS_GET_CARD_LIST_BY_STORE_ID,
				obj,
				WebServiceUrlPortManager.ACTION_URL_PORT_GET_CARD_BY_STORE_ID, 
				this,
				WebServiceAsyncServiceHelper.TYPE_HTTP_GET_INSTREAM);
		webService.setPostExecute(new PostExecute() {
			@Override
			public void onAsyncServiceComplete(int token, Object result,
					int index) {
				cardBagInfos.clear();
				ResponseBean response = WebServiceUtils
						.getObjectResultToBaseInfo(result, CardBagModel.class);
				if(response.getStatus() != ApplicationManager.RESPONSE_OK){
					for(BaseModel info : response.getReturnList()){
						cardBagInfos.add((CardBagModel)info);
					}
					if(adapter == null){
						adapter = new CardItemAdapter(cardBagInfos, mContext);
					}
					adapter.setList(cardBagInfos);
					scrollViewRefresh.onRefreshComplete();
				}else {
					Tools.showToast(mContext, response.getMessage());
					return;
				}
				
			}
		});
	}
	public void getCardList() {
		WebServiceAsyncService webService = new WebServiceAsyncService();
		webService.setParameterToAsyncService(mContext,
				webService.getNextToken(), Operation.OP_SERVICE_ARG_CARD_INFO,
				WebServiceRegistrationParameter.CARD_INFO_PARAMETER,
				new String[] { usrInfo.getUsrMobile() },
				WebServiceUrlPortManager.ACTION_URL_PORT_CARD_INFO, this,
				WebServiceAsyncServiceHelper.TYPE_HTTP_GET_INSTREAM);
		webService.setPostExecute(new PostExecute() {
			@Override
			public void onAsyncServiceComplete(int token, Object result,
					int index) {
				ResponseBean response = WebServiceUtils
						.getObjectResultToBaseInfo(result, CardBagModel.class);

				List<? extends BaseModel> list = response.getReturnList();
				cardBagInfos.clear();
				for (BaseModel info : list) {
					cardBagInfos.add((CardBagModel) info);
				}
				if (cardBagInfos.size() == 0 && nameVal.isShown()) {
					Tools.showToast(mContext, R.string.card_detail_no_card_data);
				}
				if(adapter == null){
					adapter = new CardItemAdapter(cardBagInfos, mContext);
				}
				adapter.setList(cardBagInfos);
				scrollViewRefresh.setAdapter(adapter);
				cardIssuersListStrings = new String[cardBagInfos.size()];
				cardIssuersListStrings = getCardIssuersList(cardBagInfos);
				scrollViewRefresh.onRefreshComplete();
				isSearchButtonShow = true;
				setSearchButton();
			}
		});

	}

	/*
	 * private void addChildView(ArrayList<CardBagModel> cardBagInfos){
	 * for(CardBagModel info : cardBagInfos){
	 * CardBagUtils.addCardContent(mContext, mContentLayout, info); } }
	 */
	@Override
	public void onClick(View v) {

		if (v == mPendingOrder) {
			/*
			 * FragmentManager manager = mContext.getSupportFragmentManager();
			 * FragmentTransaction ft = manager.beginTransaction(); Fragment
			 * unpayForm = new UnpayFormFragment(); ft.add(R.id.frame_container,
			 * unpayForm); ft.addToBackStack("unpayForm"); ft.commit();
			 */
			CardController.getInstance(mContext).sendEvent(
					EventType.UNPAY_ORDER_LIST);

		}
		if (v == searchBoxToggleButton) {
			if(ApplicationManager.IS_CARD_LIST_BY_STORE_ID == true){
				ApplicationManager.IS_CARD_LIST_BY_STORE_ID = false;
				isSearchButtonShow = false;
				setSearchButton();
				doAsyncService();
				titleTv.setText(R.string.tab_menu_card_bag);
				return;
			}
			if (searchBar.getVisibility() == View.GONE) {
				if (isSearchButtonShow) {
					searchBar.setVisibility(View.VISIBLE);
					isSearchButtonShow = false;
				} else {
					isSearchButtonShow = true;
					adapter.setList(cardBagInfos);
				}

			} else if (searchBar.getVisibility() == View.VISIBLE) {
				searchBar.setVisibility(View.GONE);
				InputMethodManager imm = (InputMethodManager) mContext
						.getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

				isSearchButtonShow = true;
			}
			setSearchButton();
		}
		if (v == searchButton) {

			if (TextUtils.isEmpty(searchBox.getText())) {
				Tools.showToast(
						mContext,
						mContext.getString(R.string.card_detail_search_no_key_words_remind));
				return;
			} else {
				InputMethodManager imm = (InputMethodManager) mContext
						.getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
				searchBar.setVisibility(View.GONE);
				ArrayList<CardBagModel> destinyArray = doSearch(
						cardIssuersListStrings, cardBagInfos, searchBox
								.getText().toString());
				adapter.setList(destinyArray);
				isSearchButtonShow = false;
				searchBox.setText("");
				setSearchButton();
			}

		}
	}

	@Override
	public void cancelUpdate(Object... params) {
		// TODO Auto-generated method stub

	}

	public String[] cardTypeList(ArrayList<CardBagModel> list) {
		String[] cardTypeList = new String[list.size()];
		for (int i = 0; i < list.size(); i++) {
			cardTypeList[i] = list.get(i).getCardType();
		}
		return cardTypeList;
	}

	private String[] getCardIssuersList(ArrayList<CardBagModel> list) {
		String[] cardIssuerList = new String[list.size()];
		for (int i = 0; i < list.size(); i++) {
			cardIssuerList[i] = list.get(i).getCardIssuer();
		}
		return cardIssuerList;
	}

	private ArrayList<CardBagModel> doSearch(String[] issuerList,
			ArrayList<CardBagModel> destinyList, String filter) {
		ArrayList<CardBagModel> returnList = new ArrayList<CardBagModel>();
		for (int i = 0; i < issuerList.length; i++) {
			if (issuerList[i].toLowerCase().contains(filter.toLowerCase())) {
				returnList.add(destinyList.get(i));
			}
		}
		return returnList;
	}

	class CardItemAdapter extends BaseAdapter {

		private ArrayList<CardBagModel> cardItemList;
		private Context mContext;
		private LayoutInflater inflater;

		public CardItemAdapter(ArrayList<CardBagModel> list, Context context) {
			this.cardItemList = list;
			this.mContext = context;
			inflater = (LayoutInflater) mContext
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public void setList(ArrayList<CardBagModel> list) {
			this.cardItemList = (ArrayList<CardBagModel>) list.clone();
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return cardItemList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final int _position = position;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.card_content, null);
			}
			CardBagModel info = cardItemList.get(position);
			((TextView) convertView
					.findViewById(R.id.tv_card_list_item_card_name))
					.setText(info.getCardIssuer());
			ImageView background = (ImageView) convertView
					.findViewById(R.id.iv_card_list_item_card_icon);
			if (CardTypeUtil.STR_CARD_TYPE_NUMBER.equals(info.getCardType())) {
				background.setImageResource(R.drawable.card_type_number_bg);
			} else if (CardTypeUtil.STR_CARD_TYPE_MULTIPLE.equals(info
					.getCardType())) {
				if (CardTypeUtil.STR_CARD_ATTR_VALUE.equals(info.getCardAttr())) {
					background.setImageResource(R.drawable.card_attr_value_bg);
				} else if (CardTypeUtil.STR_CARD_ATTR_POINTS.equals(info
						.getCardAttr())) {
					background.setImageResource(R.drawable.card_attr_point_bg);
				} else if (CardTypeUtil.STR_CARD_ATTR_DISCOUNT.equals(info
						.getCardAttr())) {
					background
							.setImageResource(R.drawable.card_attr_discount_bg);
				} else {
					background
							.setImageResource(R.drawable.card_type_multiple_bg);
				}
			}

			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent i = new Intent(mContext, MyCardDetailActivity.class);
					i.putExtra(ApplicationManager.INTENT_KEY,
							cardItemList.get(_position));
					mContext.startActivity(i);
				}
			});
			convertView.setTag(position);
			return convertView;
		}

	}

	@Override
	public void onRefresh() {
		doAsyncService();
	}

	private void setSearchButton() {
		if (isSearchButtonShow == true) {
			searchBoxToggleButton
					.setBackgroundResource(R.drawable.card_detail_search_selector);
		} else {
			searchBoxToggleButton
					.setBackgroundResource(R.drawable.card_detail_search_cancle_search_selector);
		}
	}
}
